import { StyleSheet, TouchableOpacity, Image } from 'react-native';
import React, { useEffect, useState, useRef } from 'react';
import Entypo from 'react-native-vector-icons/Entypo';
import { CommonStyle } from '../common/commonStyle.ts';
import { launchImageLibrary, launchCamera } from 'react-native-image-picker';
import { Actionsheet, View, Text, useDisclose } from 'native-base';
import Video, { VideoRef } from 'react-native-video';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { useBoolean } from 'ahooks';
import { MediaType } from 'react-native-image-picker/src/types.ts';
import { FasterImageView } from '@candlefinance/faster-image';
import ImageViewing from 'react-native-image-viewing';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
interface IUploadMediaProps {
  mediaType: MediaType;
  onChange: (uri: string) => void;
}

const UploadMedia: React.FC<IUploadMediaProps> = ({ onChange, mediaType }) => {
  const [uri, setUrl] = useState<string>('');
  const [paused, { setTrue, setFalse }] = useBoolean(true);
  const [visible, setIsVisible] = useState<boolean>(false);
  const { isOpen, onOpen, onClose } = useDisclose();
  const videoRef = useRef<VideoRef>(null);

  useEffect(() => {
    if (uri) onChange(uri);
  }, [uri]);

  const hadnleUploadFile = (type: string) => {
    // shoot调用摄像头  album 从图库中选择
    if (type === 'shoot') {
      launchCamera({ mediaType }).then(async (res) => {
        if (res.didCancel) return;
        const uri: string = res.assets![0].uri!;
        setUrl(uri);
      });
    } else {
      launchImageLibrary({ selectionLimit: 1, mediaType }).then(async (res) => {
        if (res.didCancel) return;
        const uri: string = res.assets![0].uri!;
        setUrl(uri);
      });
    }
    onClose();
  };

  const renderSelectFile = () => {
    return (
      <TouchableOpacity style={styles.root} onPress={onOpen}>
        <Entypo name={mediaType === 'video' ? 'video-camera' : 'folder-images'} color={CommonStyle.mainColor} size={46}></Entypo>
        <Text>点击添加{mediaType === 'video' ? '视频' : '照片'}</Text>
      </TouchableOpacity>
    );
  };

  // 视频结束播放
  const handleEndVideo = () => {
    setTrue();
    videoRef.current?.seek(0);
  };

  const renderMedia = () => {
    return (
      <React.Fragment>
        <View style={styles.root}>
          {mediaType === 'video' && <Video ref={videoRef} resizeMode="cover" source={{ uri }} controls={!paused} paused={paused} style={{ width: '100%', height: 200 }} onEnd={handleEndVideo} />}
          {mediaType === 'photo' && (
            <Touchable style={{ width: '100%', height: '100%' }} onPress={() => setIsVisible(true)}>
              <FasterImageView style={{ width: '100%', height: '100%' }} source={{ url: uri, transitionDuration: 0.3, resizeMode: 'cover', cachePolicy: 'discWithCacheControl', showActivityIndicator: true }} />
            </Touchable>
          )}
          {paused && mediaType === 'video' && (
            <View position={'absolute'} flex={1} width={'100%'} height={'100%'} justifyContent={'center'} alignItems={'center'} style={{ backgroundColor: 'rgba(0,0,0,0.3)' }}>
              <MaterialCommunityIcons name="play-circle" color={'white'} size={80} onPress={setFalse} />
            </View>
          )}
          {paused && <MaterialCommunityIcons style={{ position: 'absolute', top: -6, right: -4 }} name="close-box" color={'red'} size={40} onPress={() => setUrl('')} />}
        </View>

        <ImageViewing images={[{ uri }]} imageIndex={0} visible={visible} onRequestClose={() => setIsVisible(false)} />
      </React.Fragment>
    );
  };

  return (
    <>
      {uri && renderMedia()}
      {!uri && renderSelectFile()}
      <Actionsheet isOpen={isOpen} onClose={onClose}>
        <Actionsheet.Content>
          <Actionsheet.Item
            onPress={() => {
              hadnleUploadFile('shoot');
            }}
          >
            相机拍摄
          </Actionsheet.Item>
          <Actionsheet.Item
            onPress={() => {
              hadnleUploadFile('album');
            }}
          >
            从相册中选择
          </Actionsheet.Item>
        </Actionsheet.Content>
      </Actionsheet>
    </>
  );
};

const styles = StyleSheet.create({
  root: { borderWidth: 1, height: 200, width: '100%', borderColor: '#ccc', borderRadius: 8, alignItems: 'center', justifyContent: 'center', overflow: 'hidden' },
  videoLog: { width: 40, height: 40, marginBottom: 8 },
});

export default UploadMedia;
